package com.itheima.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.DishDao;
import com.itheima.dao.DishFlavorDao;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishDto;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional//添加事务
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {
    @Autowired
    private DishFlavorDao dishFlavorDao;


    @Override
    public void Add(DishDto dishDto) {

        //添加
        save(dishDto);
        //添加口味
        extracted(dishDto);
    }

    @Override
    public void updateA(DishDto dishDto) {
        //修改菜品信息
        updateById(dishDto);

        List<DishFlavor> flavors = dishDto.getFlavors();

        if (flavors != null) {
            for (DishFlavor flavor : flavors) {
                //将口味信息全部删除
                QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
                wrapper.eq("dish_id", dishDto.getId());
                dishFlavorDao.delete(wrapper);
            }
        }
        //重新添加口味信息
        extracted(dishDto);
    }

    //添加口味
    private void extracted(DishDto dishDto) {
        //判断是否选择口味
        if (dishDto.getFlavors() != null) {
            //遍历所有口味
            for (DishFlavor flavor : dishDto.getFlavors()) {
                //获取当前dish的id
                flavor.setDishId(dishDto.getId());
                //添加
                dishFlavorDao.insert(flavor);
            }
        }
    }


}
